package com.mz.ozy.activity.c2c;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.mz.ozy.R;
import com.mz.ozy.adapter.BuyKtPopGridAdapter;
import com.mz.ozy.adapter.PhotoAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.OrderDetailBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.BuyKtPresenter;
import com.mz.ozy.mvp.view.BuyKtContract;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.StringUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.CustomGridView;
import com.mz.ozy.widget.CustomPopWindow;
import com.mz.ozy.widget.dialog.AiliPayCodeDialog;
import com.mz.ozy.widget.dialog.OrderConfirmPayDialog;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BuyKtActivity extends BaseActivity<BuyKtContract.View, BuyKtPresenter> implements BuyKtContract.View {

    @BindView(R.id.tv_usdt_num)
    TextView mTvUsdtNum;
    @BindView(R.id.tv_sell_state)
    TextView mTvSellState;
    @BindView(R.id.tv_buykt_price)
    TextView mTvBuyktPrice;
    @BindView(R.id.tv_buykt_num)
    TextView mTvBuyktNum;
    @BindView(R.id.tv_count_down)
    TextView mTvCountDown;

    @BindView(R.id.tv_receive_name)
    TextView mTvReceiveName;
    @BindView(R.id.tv_card_num)
    TextView mTvCardNum;
    @BindView(R.id.iv_alipay_code)
    ImageView mIvAlipayCode;
    @BindView(R.id.tv_card_bank)
    TextView mTvCardBank;
    @BindView(R.id.tv_pay_type)
    TextView mTvPayType;
    @BindView(R.id.tv_pay_label)
    TextView mTvPayLabel;
    @BindView(R.id.tv_card_num_label)
    TextView mTvCardNumLabel;

    @BindView(R.id.tv_real_name)
    TextView mTvRealName;
    @BindView(R.id.tv_tele_num)
    TextView mTvTeleNum;
    @BindView(R.id.tv_order_num)
    TextView mTvOrderNum;
    @BindView(R.id.tv_pay_num)
    TextView mTvPayNum;
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;

    @BindView(R.id.ll_buykt_middle)
    LinearLayout mLlBuyktMiddle;
    @BindView(R.id.ll_buykt_bottom)
    LinearLayout mLlBuyktBottom;
    @BindView(R.id.tv_order_confirm)
    TextView mTvOrderConfirm;
    @BindView(R.id.tv_order_appeal)
    TextView mTvOrderAppeal;
    @BindView(R.id.ll_count_down)
    LinearLayout mLlCountDown;

    @BindView(R.id.ll_buy_appeal)
    LinearLayout mLlBuyAppeal;
    @BindView(R.id.tv_appeal_msg)
    TextView mTvAppealMsg;
    @BindView(R.id.tv_appeal_time)
    TextView mTvAppealTime;
    @BindView(R.id.gridview)
    CustomGridView mGridView;
    @BindView(R.id.rl_payment_num)
    RelativeLayout mRlPaymentNum;
    @BindView(R.id.tv_pay_unit)
    TextView mTvPayUnit;

    private CustomPopWindow mGridPopWindow;
    private BuyKtPopGridAdapter mBrandPopGridAdapter;
    private String type = "1";   //0全部,1购买KT,2购买股权积分
    private boolean isCancel = true;
    private boolean isConfirm = true;
    private List<String> mCateList = Arrays.asList("银行卡", "支付宝");
    private String orderid;
    private int transType;
    private String titleStr = "";
    private OrderDetailBean orderDetailBean;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mPresenter.geAssetsInfo(BuyKtActivity.this, orderid);
                    break;
                case 2:
                    final Long timeInt = (Long) msg.obj;
                    final String dateStr = long2DateStr(timeInt);
                    mTvCountDown.setText(dateStr);
                    break;
                default:
                    break;

            }
        }
    };

    /*定义一个倒计时的内部类*/
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            handler.sendEmptyMessage(1);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Message msg = new Message();
            msg.what = 2;
            msg.obj = millisUntilFinished / 1000;
            handler.sendMessage(msg);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_kt);
        ButterKnife.bind(this);
        initTitle();
        orderid = getIntent().getStringExtra("id");
        transType = getIntent().getIntExtra("type", 0);
        initView();
    }

    private void initView() {
        switch (transType) {
            case 1:
                titleStr = "KT";
                mTvPayUnit.setText("CNY");
                break;
            case 3:
                titleStr = "KT";
                mTvOrderConfirm.setText("付款");
                mTvPayUnit.setText("USDT");
                break;
            case 5:
                titleStr = "KT";
                mTvOrderConfirm.setText("我已付款");
                mTvPayUnit.setText("CNY");
                break;
            case 2:
                titleStr = "股权积分";
                mTvPayUnit.setText("CNY");
                break;
            case 4:
                titleStr = "股权积分";
                mTvOrderConfirm.setText("付款");
                mTvPayUnit.setText("USDT");
                break;
            case 6:
                titleStr = "股权积分";
                mTvOrderConfirm.setText("我已付款");
                mTvPayUnit.setText("CNY");
                break;
        }
        tvCenterTitle.setText("购买" + titleStr);

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                final PhotoAdapter adapter = (PhotoAdapter) mGridView.getAdapter();
                PhotoScanActivity.startPhotoScan(BuyKtActivity.this, adapter.getCourseList(), position);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.geAssetsInfo(this, orderid);
    }

    @OnClick({R.id.rl_bank_card, R.id.tv_order_confirm, R.id.tv_order_appeal, R.id.iv_alipay_code
            , R.id.tv_copy1, R.id.tv_copy2, R.id.tv_copy3, R.id.tv_copy4, R.id.tv_copy5, R.id.tv_copy6})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_bank_card:
//                showPopListView();
                break;
            case R.id.tv_order_confirm:
                if (isConfirm) {
                    showSportsHarmDialog();
                } else {
                    Intent intent1 = new Intent(this, AppealActivity.class);
                    intent1.putExtra("id", orderid + "");
                    intent1.putExtra("userType", "0");
                    startActivity(intent1);
                }
                break;
            case R.id.tv_order_appeal:
                if (isCancel) {
                    mPresenter.cancelOrder(this, orderid);
                } else {
                    Intent intent1 = new Intent(this, AppealActivity.class);
                    intent1.putExtra("id", orderid + "");
                    intent1.putExtra("userType", "0");
                    startActivity(intent1);
                }
                break;
            case R.id.iv_alipay_code:
                if ("0".equals(type)) {
                    final String cardbank = mTvCardNum.getText().toString().trim();
                    copyMsg(cardbank);
                } else {
                    final OrderDetailBean.AMapBean aMapBean = orderDetailBean.getaMap();
                    AiliPayCodeDialog mSportsHarmDialog = new AiliPayCodeDialog(this, aMapBean.getAlipayCollectionCode());
                    mSportsHarmDialog.setOnDialogListener(new AiliPayCodeDialog.onDialogListener() {
                        @Override
                        public void onCancel() {
                            mSportsHarmDialog.toggleDialog();
                        }
                    });
                    mSportsHarmDialog.toggleDialog();
                }
                break;
            case R.id.tv_copy1:
                copyMsg(mTvReceiveName.getText().toString().trim());
                break;
            case R.id.tv_copy2:
                copyMsg(mTvCardBank.getText().toString().trim());
                break;
            case R.id.tv_copy3:
                copyMsg(mTvRealName.getText().toString().trim());
                break;
            case R.id.tv_copy4:
                copyMsg(mTvTeleNum.getText().toString().trim());
                break;
            case R.id.tv_copy5:
                copyMsg(mTvOrderNum.getText().toString().trim());
                break;
            case R.id.tv_copy6:
                copyMsg(mTvPayNum.getText().toString().trim());
                break;
        }
    }

    private void copyMsg(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("msg", msg);
            cm.setPrimaryClip(mClipData);
            ToastUtils.showToast("复制成功");
        }
    }

    private void showSportsHarmDialog() {
        OrderConfirmPayDialog mSportsHarmDialog = new OrderConfirmPayDialog(this);
        mSportsHarmDialog.setOnDialogListener(new OrderConfirmPayDialog.onDialogListener() {
            @Override
            public void onSubmit(String msg) {
                submitPayOrder(msg);
                mSportsHarmDialog.toggleDialog();
            }

            @Override
            public void onCancel() {
                mSportsHarmDialog.toggleDialog();
            }
        });
        mSportsHarmDialog.toggleDialog();
    }

    private void submitPayOrder(String msg) {
        mPresenter.onPay(this, orderid, msg);
    }

    private void showPopListView() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_buykt_grid, null);
        //处理popWindow 显示内容
        handleGridView(contentView);
        //创建并显示popWindow
        mGridPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .create()
                .showAsDropDown(titleBar);
    }

    private void handleGridView(View contentView) {
        GridView gridview = (GridView) contentView.findViewById(R.id.gridview);
        contentView.findViewById(R.id.view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGridPopWindow != null) {
                    mGridPopWindow.dissmiss();
                }
            }
        });
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mGridPopWindow.dissmiss();
                mBrandPopGridAdapter.setSelectPosition(i);
                mBrandPopGridAdapter.notifyDataSetChanged();
                type = String.valueOf(i);
                final OrderDetailBean.AMapBean aMapBean = orderDetailBean.getaMap();
                if (i == 0) {
                    mTvPayType.setText("银行卡");
                    mTvPayType.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_bank_card, 0, 0, 0);
                    mTvPayLabel.setText("开户银行");
                    mTvCardNumLabel.setText("银行卡号");
                    mTvCardBank.setText(aMapBean.getBankAccount());
                    mTvCardNum.setText(aMapBean.getBankCardNumber());
                    mIvAlipayCode.setImageResource(R.mipmap.buy_complete_copy);
                } else {
                    mTvPayType.setText("支付宝");
                    mTvPayType.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_pay_alipay, 0, 0, 0);
                    mTvPayLabel.setText("支付宝帐号");
                    mTvCardNumLabel.setText("收款二维码");
                    mTvCardBank.setText(aMapBean.getAlipayAccount());
                    mTvCardNum.setText("");
                    mIvAlipayCode.setImageResource(R.mipmap.icon_alipay_qrcode);
                }
            }
        });
        if (mCateList != null) {
            mBrandPopGridAdapter = new BuyKtPopGridAdapter(this, type, mCateList);
            gridview.setAdapter(mBrandPopGridAdapter);
        }
    }

    @Override
    public void geAssetsInfoSuccess(OrderDetailBean bean) {
        orderDetailBean = bean;
        final OrderDetailBean.OrderMapBean orderMap = bean.getOrderMap();
        if (orderMap != null) {
            mTvBuyktPrice.setText(getString(R.string.buy_kt_price_format, StringUtils.formattingDecimal(orderMap.getBuyprice(), 2)));
            mTvBuyktNum.setText(getString(R.string.buy_kt_num_format, orderMap.getNum()) + titleStr);
            setOrderState(orderMap.getDateOfExpiry(), orderMap.getState());
            mTvOrderNum.setText(orderMap.getTesq());
            mTvPayNum.setText(orderMap.getPaymentVoucher());

            switch (orderMap.getTranType()) {
                case 3:
                case 4:
                    final String usdtbycny = SPUtils.getInstance(this).getString(Constants.SPName.USDTBYCNY, "");
                    mTvUsdtNum.setText(Utils.decimalUtils(new BigDecimal(orderMap.getAmount()).divide(new BigDecimal(usdtbycny)) + ""));
                    mLlBuyktMiddle.setVisibility(View.GONE);
                    break;
                case 5:
                case 6:
                default:
                    mTvUsdtNum.setText(StringUtils.formattingDecimal(orderMap.getAmount(), 2));
                    final OrderDetailBean.AMapBean aMapBean = bean.getaMap();
                    if (aMapBean != null) {
                        mTvReceiveName.setText(aMapBean.getUsername());
                        mTvCardNum.setText(aMapBean.getBankCardNumber());
                        mTvCardBank.setText(aMapBean.getBankAccount());
                    }
                    break;
            }

        }

        final OrderDetailBean.AMapBean aMapBean = bean.getaMap();
        if (aMapBean != null) {
            mTvOrderTime.setText(aMapBean.getCreateTime().substring(0, aMapBean.getCreateTime().length() - 2));
            mTvRealName.setText(aMapBean.getUsername());
        }

        final OrderDetailBean.UserMapBean user = bean.getUser();
        if (user != null) {
            mTvTeleNum.setText(user.getUserphone());
        }
    }

    @Override
    public void onPaySuccess(OrderDetailBean bean) {
        ToastUtils.showToast("已确认付款");
        mPresenter.geAssetsInfo(this, orderid);
    }

    @Override
    public void cancelOrderSuccess(OrderDetailBean bean) {
        ToastUtils.showToast("取消订单成功");
        mPresenter.geAssetsInfo(this, orderid);
    }

    private MyCount mc;

    private void setOrderState(String dateOfExpiry, int state) {
        switch (state) {
            case 0:
                mTvSellState.setText("待付款");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));
                startCountDown(dateOfExpiry, 0);
                break;
            case 1:
            case 7:
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("待确认");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));
                startCountDown(dateOfExpiry, 1);
                break;
            case 5:
                mLlCountDown.setVisibility(View.GONE);
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("申诉中");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));

                mLlBuyAppeal.setVisibility(View.VISIBLE);
                final OrderDetailBean.AppleMapBean appleMap = orderDetailBean.getAppleMap();
                mTvAppealMsg.setText(appleMap.getAppealReason());
                mTvAppealTime.setText(appleMap.getCreateTime().substring(0, appleMap.getCreateTime().length() - 2));
                final String[] imageStr = appleMap.getAppealAttachment().split(",");
                PhotoAdapter adapter = new PhotoAdapter(this, Arrays.asList(imageStr));
                mGridView.setAdapter(adapter);
                break;
            case 2:
            case 4:
            case 6:
                mLlCountDown.setVisibility(View.GONE);
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("已完成");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                mLlBuyktMiddle.setVisibility(View.GONE);
                mRlPaymentNum.setVisibility(View.GONE);
                break;
            case 3:
            case 9:
            case 10:
                mLlCountDown.setVisibility(View.GONE);
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("已取消");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
            case 8:
                isCancel = false;
                mLlCountDown.setVisibility(View.GONE);
                mTvOrderConfirm.setVisibility(View.GONE);
                mTvOrderAppeal.setBackgroundColor(ContextCompat.getColor(this, R.color.c_063eff));
                mTvOrderAppeal.setTextColor(ContextCompat.getColor(this, R.color.white));
                mTvOrderAppeal.setText("申诉");
                mTvSellState.setText("超时未确认");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
            case 11:
                mLlCountDown.setVisibility(View.GONE);
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("超时未付款");
                break;
        }
    }


    private void startCountDown(String dateOfExpiry, int type) {
        try {
            final long nowInt = Utils.getCurDateIntTime();
            final long endtimeInt = Utils.parseDateIntTime(dateOfExpiry);
            if (endtimeInt > nowInt) {
                final long spaceTimeInt = endtimeInt - nowInt;
                final String dateStr = long2DateStr(spaceTimeInt / 1000);
                mTvCountDown.setText(dateStr);
                mc = new MyCount(spaceTimeInt, 1000);
                mc.start();
            } else {
                isConfirm = false;
                mLlCountDown.setVisibility(View.GONE);
                if (type == 0) {
                    mLlBuyktBottom.setVisibility(View.GONE);
                    mTvSellState.setText("超时未支付");
                } else {
                    mLlBuyktBottom.setVisibility(View.VISIBLE);
                    mTvSellState.setText("超时未确认");
                    mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                    mTvOrderConfirm.setText("申诉");
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private String long2DateStr(Long timeInt) {
        final int h = Utils.generateH(timeInt);
        final int m = Utils.generateM(timeInt);
        final int s = Utils.generateS(timeInt);
        String timestr = "";
        if (h >= 10) {
            timestr = timestr + h;
            timestr = timestr + ":";
        } else {
            if (h > 0) {
                timestr = timestr + "0" + h;
                timestr = timestr + ":";
            }
        }
        if (m >= 10) {
            timestr = timestr + m;
        } else {
            timestr = timestr + "0" + m;
        }
        timestr = timestr + ":";
        if (s >= 10) {
            timestr = timestr + s;
        } else {
            timestr = timestr + "0" + s;
        }
        return timestr;
    }
}
